import { Button, Checkbox, Input, Message, Tabs } from '@arco-design/web-react';
import { useEffect, useState } from 'react';
import { copyToClipboard } from '../../../utils/utils';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { cloneDeep } from '../../../utils/utils';
import { apiGetPreSetConvertUrl, apiSetPreSetConvertUrl } from '../../../api';
import { CardDetail, CardPreSetConvert } from '../../../types';

interface Props {
  isSave: boolean;
  item?: CardDetail;
  onCancel?: () => void;
}

export default function PreSetConvertUrlDialog({ item, isSave, onCancel }: Props) {
  const [activeTab, setActiveTab] = useState('1');

  const [searchValue, setSearchValue] = useState('');

  const [phoneData, setPhoneData] = useState<CardPreSetConvert>({});
  const [flowData, setFlowData] = useState<CardPreSetConvert>({});
  const [emData, setEmData] = useState<CardPreSetConvert>({});

  const [copyStr, setCopyStr] = useState('');

  useEffect(() => {
    loadData('1');
  }, []); // eslint-disable-line

  useEffect(() => {
    createStr();
  }, [phoneData, flowData, emData, activeTab]); // eslint-disable-line

  function getData(type: string) {
    let detailData: CardPreSetConvert = {};
    if (type === '1') {
      detailData = flowData;
    } else if (type === '3') {
      detailData = emData;
    } else {
      detailData = phoneData;
    }
    return detailData;
  }
  function setData(type: string, data: CardPreSetConvert) {
    if (type === '1') {
      setFlowData(data);
    } else if (type === '3') {
      setEmData(data);
    } else {
      setPhoneData(data);
    }
  }

  async function loadData(type: string) {
    let t = getData(type);
    if (t.loaded) {
      return;
    }
    LoadingMask.show('正在加载...');
    try {
      let res = await apiGetPreSetConvertUrl(type, item?.iccid);
      let data = res.data;
      if (data.code === 200) {
        let _data = Object.assign({}, data.data, { loaded: true, type, saved: false });
        setData(type, _data);
      } else {
        Message.warning(data.msg ?? '加载失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '加载失败');
    } finally {
      LoadingMask.hide();
    }
  }

  function handleChange(key: string, value: any) {
    let t = cloneDeep(getData(activeTab));
    t[key] = value;
    t.saved = false;
    setData(activeTab, t);
  }

  function createStr() {
    let str = (detailData.beforText ?? '') + '\n';
    (detailData.productList ?? []).forEach((i) => {
      let _jgn = activeTab === '3' ? (i.jstGoodsNo ?? '') + ',' : '';
      if (detailData.businessJson?.includes(_jgn + i.productId!)) {
        str += '【' + i.productName + '】\n';
        str += i.shortUrl + '\n';
      }
    });
    str += detailData.afterText ?? '';
    setCopyStr(str);
  }

  async function handleSave() {
    LoadingMask.show('正在保存...');
    try {
      let res = await apiSetPreSetConvertUrl(
        activeTab,
        detailData.beforText ?? '',
        detailData?.afterText ?? '',
        detailData?.businessJson ?? []
      );
      let data = res.data;
      if (data.code === 200) {
        setData(activeTab, { ...detailData, saved: true });
        Message.success(data.msg ?? '保存成功');
      } else {
        Message.warning(data.msg ?? '保存失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '保存失败');
    } finally {
      LoadingMask.hide();
    }
  }

  function handleConfirm() {
    copyToClipboard(copyStr);
    if (onCancel) {
      onCancel();
    }
  }

  let detailData = getData(activeTab);
  let productList = detailData.productList ?? [];
  if (searchValue)
    productList = productList.filter((i) => {
      let _jgn = activeTab === '3' ? (i.jstGoodsNo ?? '') + ',' : '';
      return (_jgn + i.productName)?.includes(searchValue);
    });

  let children = (
    <>
      <Tabs
        className="bw-100"
        activeTab={activeTab}
        onChange={(v) => {
          loadData(v);
          setActiveTab(v);
        }}
      >
        <Tabs.TabPane key="1" title="号卡预设"></Tabs.TabPane>
        {/* <Tabs.TabPane key="1" title="流量卡预设"></Tabs.TabPane> */}
        <Tabs.TabPane key="3" title="设备预设"></Tabs.TabPane>
      </Tabs>
      <div className="h-400 d-flex-r p-10">
        <div className="flex-1 d-flex-c">
          <div className="font-12 text-second-color">前置话术</div>
          <Input.TextArea
            className="m-input"
            autoSize={{ minRows: 2, maxRows: 2 }}
            placeholder="前置话术"
            value={detailData.beforText}
            onChange={(v) => handleChange('beforText', v)}
          />
          <Input
            className="m-input mt-10"
            placeholder="搜索商品"
            value={searchValue}
            onChange={(v) => setSearchValue(v)}
          />
          <div className="flex-1 h-1 scroll-bar-h-min mt-10 mb-10 overflow-y">
            {productList.map((i) => {
              let _jgn = activeTab === '3' ? (i.jstGoodsNo ?? '') + ',' : '';
              return (
                <div key={_jgn + i.productId} className="d-flex-r p-10">
                  <Checkbox
                    checked={detailData.businessJson?.includes(_jgn + i.productId!)}
                    onChange={() =>
                      handleChange(
                        'businessJson',
                        detailData.businessJson?.includes(_jgn + i.productId!)
                          ? detailData.businessJson?.filter((j) => j !== _jgn + i.productId)
                          : [...(detailData.businessJson ?? []), _jgn + i.productId!]
                      )
                    }
                  >
                    {_jgn + i.productName}
                  </Checkbox>
                </div>
              );
            })}
          </div>
          <div className="font-12 text-second-color">后置话术</div>
          <Input.TextArea
            className="m-input"
            autoSize={{ minRows: 2, maxRows: 2 }}
            placeholder="后置话术"
            value={detailData.afterText}
            onChange={(v) => handleChange('afterText', v)}
          />
        </div>

        <div className="flex-1 pl-20">
          <Input.TextArea
            disabled={isSave}
            className="m-input"
            autoSize={{ minRows: 4, maxRows: 17 }}
            value={copyStr}
            onChange={(v) => setCopyStr(v)}
          />
        </div>
      </div>
    </>
  );

  if (isSave) {
    return (
      <div className=" pl-20 pr-20 page list-page">
        {children}
        <div className="d-flex-r jc-center mt-10">
          <Button type="primary" disabled={detailData.saved} onClick={handleSave}>
            保存
          </Button>
          <Button
            type="primary"
            className="ml-20"
            onClick={() => {
              if (!copyStr) {
                return Message.warning('请配置内容');
              }
              copyToClipboard(copyStr);
            }}
          >
            复制
          </Button>
        </div>
      </div>
    );
  }
  return (
    <DetailModal
      className="bw-80"
      show
      title="推广预设"
      cancelBtnShow={false}
      onCancel={onCancel}
      onConfirm={handleConfirm}
      confirmText="复制"
    >
      <div className="bw-100">{children}</div>
    </DetailModal>
  );
}
